//
//  playerPayViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 16/8/24.
//  Copyright © 2016年 宋旭东. All rights reserved.
//
#define leftMargin 20
#import "playerPayViewController.h"
#import "playerPayPriceView.h"
#import "playerAddressViewController.h"
#import "AppDelegate.h"
#import "UIViewExt.h"
#import "UIImage+tint.h"
#import "AliPayModel.h"
#import "JSONKit.h"
@interface playerPayViewController ()<UITextViewDelegate>
{
    NSString *totalPriceStr;
    
}
@property (strong, nonatomic) NSString *workName;
@property (strong, nonatomic) NSString *workID;
@property (strong, nonatomic) NSString *priceString;
@property (strong, nonatomic) NSString *loveCount;
@property (strong, nonatomic) NSString *commentCount;
@property (strong, nonatomic) NSArray *priceArray;
@property (strong, nonatomic) NSArray *tagArray;
@property (strong, nonatomic) UIImage *coverImage;
@property (strong, nonatomic) UIImageView *likeImageView;
@property (strong, nonatomic) UIImageView *commentImageView;
@property (strong, nonatomic) UILabel *likeLable;
@property (strong, nonatomic) UILabel *commentLable;
@property (strong, nonatomic) UITextView *addressView;
@property (strong, nonatomic) UILabel *totalPriceLabel;
@end

@implementation playerPayViewController
- (instancetype)initWithworkName:(NSString *)workName priceArray:(NSArray *)priceArray price:(NSString *)price tags:(NSArray *)tags loveCount:(NSString *)loveCount commentCount:(NSString *)commentCount cover:(UIImage *)cover workid:(NSString *)workid;
{
    self = [super init];
    if (self) {
        self.workName = workName;
        self.workID = workid;
        self.priceString = price;
        self.loveCount = loveCount;
        self.commentCount = commentCount;
        self.tagArray = tags;
        self.priceArray = priceArray;
//        if (priceArray.count == 0) {
//            _priceArray = [NSArray arrayWithObjects:@"300",@"600",@"900",@"999", nil];
//        }
        self.coverImage = cover;
    }
    return self;
}
- (void)backToPlayer:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
     [AppDelegate shareDelegate].playerStateBtn.hidden = YES;
    [self setAddressViewText];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付";
    self.navigationController.navigationBar.translucent = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"payNote"];
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    [back setFrame:CGRectMake(0, 0, 30, 30)];
    [back setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(backToPlayer:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:back];
    self.navigationItem.leftBarButtonItem = backItem;
    // Do any additional setup after loading the view.
    [self createWorkInfoView];
    [self createPriceView];
    [self createAddressViewAndPayButton];
}
- (void)createWorkInfoView
{
    UIImageView *coverImageView = [[UIImageView alloc] initWithImage:_coverImage];
    coverImageView.frame = CGRectMake(leftMargin, leftMargin, 5 * leftMargin, 5 * leftMargin);
    [self.view addSubview:coverImageView];
    
    UILabel *workNameLable = [[UILabel alloc] initWithFrame:CGRectMake(coverImageView.right + leftMargin, coverImageView.top, self.view.width - coverImageView.right - 2 * leftMargin, 1.5 * leftMargin)];
    workNameLable.text = _workName;
    workNameLable.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:workNameLable];
    
    
    self.likeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(coverImageView.right + leftMargin, coverImageView.bottom - 20, 20, 20)];
    _likeImageView.image = [[UIImage imageNamed:@"Play_love_no"] imageWithTintColor:[UIColor colorWithRed:0.690 green:0.690 blue:0.690 alpha:1.00] blendMode:kCGBlendModeColor];
    [self.view addSubview:_likeImageView];
    self.likeLable = [[UILabel alloc] initWithFrame:CGRectMake(_likeImageView.right, _likeImageView.top, 50, _likeImageView.height)];
    _likeLable.font = [UIFont systemFontOfSize:14];
    _likeLable.text = _loveCount;
    _likeLable.textColor = [UIColor colorWithRed:0.690 green:0.690 blue:0.690 alpha:1.00];
    CGSize likeSize = [self getSizeOfString:_likeLable.text font:_likeLable.font];
    _likeLable.frame = CGRectMake(_likeImageView.right, _likeImageView.top, likeSize.width, _likeImageView.height);
    //    _likeLable.text = @"88888";
    [self.view addSubview:_likeLable];
    
    
    self.commentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(_likeLable.right + 15, _likeImageView.top, _likeImageView.width, _likeImageView.height)];
    _commentImageView.image = [[UIImage imageNamed:@"Play_comment_black"] imageWithTintColor:[UIColor colorWithRed:0.690 green:0.690 blue:0.690 alpha:1.00] blendMode:kCGBlendModeColor];
    [self.view addSubview:_commentImageView];
    self.commentLable = [[UILabel alloc] initWithFrame:CGRectMake(_commentImageView.right, _commentImageView.top, 50, _commentImageView.height)];
    _commentLable.font = _likeLable.font;
    _commentLable.textColor = [UIColor colorWithRed:0.690 green:0.690 blue:0.690 alpha:1.00];
    _commentLable.text = _commentCount;
    CGSize commentSize = [self getSizeOfString:_commentCount font:_commentLable.font];
    _commentLable.frame = CGRectMake(_commentLable.left, _commentLable.top, commentSize.width, _commentLable.height);
    [self.view addSubview:_commentLable];
    
    
    
    
    UITextView *tagsView = [[UITextView alloc] initWithFrame:CGRectMake(workNameLable.left, workNameLable.bottom, workNameLable.width, coverImageView.height - workNameLable.height - 25)];
    tagsView.contentInset = UIEdgeInsetsMake(-5, -5, 0, 0);
    tagsView.userInteractionEnabled = NO;
//    tagsView.backgroundColor = [UIColor blackColor];
    tagsView.textColor = [UIColor colorWithRed:0.624 green:0.624 blue:0.624 alpha:1.00];
    NSString *tagString = [_tagArray componentsJoinedByString:@"，"];
    tagsView.text = tagString;
    [self.view addSubview:tagsView];
}
- (void)createPriceView
{
    if (_priceArray.count == 0) {
        playerPayPriceView * priceView = [[playerPayPriceView alloc] initWithFrame:CGRectMake(0, _commentImageView.bottom + 2 * leftMargin, self.view.width, 30)];
        priceView.tag = 122;
        priceView.priceLabel.text = [NSString stringWithFormat:@"%@元", _priceString];
        [self.view addSubview:priceView];
        priceView.countChangeBlock = ^() {
            [self payPriceDic];
            _totalPriceLabel.text = [NSString stringWithFormat:@"合计：%@元",totalPriceStr];
        };
    } else {
        for (int i = 1; i <= _priceArray.count; i++) {
            playerPayPriceView * priceView = [[playerPayPriceView alloc] initWithFrame:CGRectMake(0, _commentImageView.bottom + i * 2 * leftMargin + (i - 1) * 10, self.view.width, 30)];
//            priceView.backgroundColor = [UIColor redColor];
            priceView.tag = i + 122;
            priceView.priceLabel.text = [NSString stringWithFormat:@"%@元", _priceArray[i - 1]];
            [self.view addSubview:priceView];
            priceView.countChangeBlock = ^() {
                [self payPriceDic];
                _totalPriceLabel.text = [NSString stringWithFormat:@"合计：%@元",totalPriceStr];
            };
        }
    }
}
- (void)createAddressViewAndPayButton
{
    
//    playerPayPriceView *priceView = [self.view viewWithTag:122 + _priceArray.count];
   
    self.addressView = [[UITextView alloc] initWithFrame:CGRectMake(leftMargin,  _commentImageView.bottom + 5.6 * 2 * leftMargin + (5 - 1) * 10 , self.view.width - 2 * leftMargin, 5.5 * leftMargin)];
    _addressView.delegate = self;
    _addressView.textColor = [UIColor colorWithRed:0.624 green:0.624 blue:0.624 alpha:1.00];
    _addressView.font = [UIFont systemFontOfSize:15];
    _addressView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 5;// 字体的行间距
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont systemFontOfSize:15],
                                 NSParagraphStyleAttributeName:paragraphStyle
                                 };
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"userAddress"]) {
        NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userAddress"];
        NSString *addressString = [NSString stringWithFormat:@"%@\t%@\n%@ %@ %@ %@\n备注：空",[dic valueForKey:@"name"],[dic valueForKey:@"phone"],[dic valueForKey:@"provinces"],[dic valueForKey:@"city"],[dic valueForKey:@"district"],[dic valueForKey:@"detail"]];
        _addressView.attributedText = [[NSAttributedString alloc] initWithString:addressString attributes:attributes];
    } else {
       
        _addressView.attributedText = [[NSAttributedString alloc] initWithString:@"请输入收件人地址信息..." attributes:attributes];
    }
    [self.view addSubview:_addressView];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, _addressView.top - 2, self.view.width, 2)];
    line.backgroundColor = [UIColor colorWithRed:0.906 green:0.906 blue:0.906 alpha:1.00];
    [self.view addSubview:line];
    
    self.totalPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(leftMargin, self.view.bottom - 5.5 * leftMargin, self.view.width - 114, 50)];
    _totalPriceLabel.text = @"合计：0.00元";
    _totalPriceLabel.textColor = [UIColor colorWithRed:1.000 green:0.047 blue:0.047 alpha:1.00];
    [self.view addSubview:_totalPriceLabel];
    
    UIButton *payButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [payButton setBackgroundColor:[UIColor colorWithRed:1.000 green:0.000 blue:0.000 alpha:1.00]];
    [payButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [payButton setTitle:@"支付" forState:UIControlStateNormal];
    payButton.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    payButton.frame = CGRectMake(self.view.width - 114, self.view.bottom - 5.5 * leftMargin, 114,  50);
    [payButton addTarget:self action:@selector(payButtonClicke:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:payButton];
    
    UIView *payLine = [[UIView alloc] initWithFrame:CGRectMake(0, payButton.top, self.view.width - 114, 1)];
    payLine.backgroundColor = [UIColor colorWithRed:0.906 green:0.906 blue:0.906 alpha:1.00];
    [self.view addSubview:payLine];
    
    UIButton *revampButton = [UIButton buttonWithType:UIButtonTypeCustom];
    revampButton.frame = CGRectMake(_addressView.right - 60, payButton.top - 60, 40, 30);
    //    [revampButton setImage:[UIImage imageNamed:@"play_pay_change_arrow"] forState:UIControlStateNormal];
    [revampButton setTitle:@"修改" forState: UIControlStateNormal];
    [revampButton setTitleColor:[UIColor colorWithRed:0.400 green:0.400 blue:0.400 alpha:1.00] forState:UIControlStateNormal];
    [revampButton addTarget:self action:@selector(revampButtonClicke:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:revampButton];
    
    UIImageView *arrowImageView = [[UIImageView alloc] initWithFrame:CGRectMake(revampButton.right + 10, revampButton.top + 7, 7, revampButton.height - 14)];
    arrowImageView.image = [UIImage imageNamed:@"play_pay_change_arrow"];
    [self.view addSubview:arrowImageView];
}
- (void)setAddressViewText
{
    if (_addressView) {
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 5;// 字体的行间距
        NSDictionary *attributes = @{
                                     NSFontAttributeName:[UIFont systemFontOfSize:15],
                                     NSParagraphStyleAttributeName:paragraphStyle
                                     };

        if ([[NSUserDefaults standardUserDefaults] objectForKey:@"userAddress"]) {
            NSString *payNoteStr;
            if (![[NSUserDefaults standardUserDefaults] valueForKey:@"payNote"]) {
                payNoteStr = @"空";
            } else {
                payNoteStr = [[NSUserDefaults standardUserDefaults] valueForKey:@"payNote"];
            }
            NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userAddress"];
            NSString *addressString = [NSString stringWithFormat:@"%@\t%@\n%@ %@ %@ %@\n备注：%@",[dic valueForKey:@"name"],[dic valueForKey:@"phone"],[dic valueForKey:@"provinces"],[dic valueForKey:@"city"],[dic valueForKey:@"district"],[dic valueForKey:@"detail"], payNoteStr];
             _addressView.attributedText = [[NSAttributedString alloc] initWithString:addressString attributes:attributes];
        } else {
             _addressView.attributedText = [[NSAttributedString alloc] initWithString:@"请输入收件人地址信息..." attributes:attributes];
        }
    }
}
- (CGSize)getSizeOfString:(NSString *)string font:(UIFont *)font
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(50 , 20) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
    CGSize size = rect.size;
    return size;
}
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    return NO;
}
- (void)revampButtonClicke:(UIButton *)sender
{
    playerAddressViewController *addressVC = [[playerAddressViewController alloc] init];
    [self.navigationController pushViewController:addressVC animated:YES];
}
- (NSDictionary *)payPriceDic
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    float totalPrice = 0;
    
    if (_priceArray.count > 1) {
        for (int i = 1; i <= _priceArray.count; i++) {
            playerPayPriceView *priceView = [self.view viewWithTag:122 + i];
            NSString *price = [priceView.priceLabel.text stringByReplacingOccurrencesOfString:@"元" withString:@""];
            NSString *count = priceView.countLabel.text;
            [dic setValue:count forKey:price];
            totalPrice = price.floatValue * count.floatValue + totalPrice;
            totalPriceStr = [NSString stringWithFormat:@"%.2f",totalPrice];
        }
    } else {
        playerPayPriceView *priceView = [self.view viewWithTag:122];
        NSString *price = [priceView.priceLabel.text stringByReplacingOccurrencesOfString:@"元" withString:@""];
        NSString *count = priceView.countLabel.text;
        [dic setValue:count forKey:price];
        totalPrice = price.floatValue * count.floatValue + totalPrice;
        totalPriceStr = [NSString stringWithFormat:@"%.2f",totalPrice];
    }
    return dic;
}
- (void)payButtonClicke:(UIButton *)sender
{
    AliPayModel *model = [[AliPayModel alloc] init];
    NSDictionary *dic = [self payPriceDic];
    NSData *priceData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *priceJSON = [[NSString alloc] initWithData:priceData encoding:NSUTF8StringEncoding];
    
    NSDictionary *addressDict = [[NSUserDefaults standardUserDefaults] objectForKey:@"userAddress"];
    NSString *addressString = [NSString stringWithFormat:@"%@%@%@%@",[addressDict valueForKey:@"provinces"],[addressDict valueForKey:@"city"],[addressDict valueForKey:@"district"],[addressDict valueForKey:@"detail"]];
    NSDictionary *addressDic = [NSDictionary dictionaryWithObjectsAndKeys:addressString,@"addr",[addressDict valueForKey:@"phone"],@"tel",[addressDict valueForKey:@"name"],@"name",[[NSUserDefaults standardUserDefaults] valueForKey:@"payNote"],@"note", nil];
    NSData *addressData = [NSJSONSerialization dataWithJSONObject:addressDic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *addressJSON = [[NSString alloc] initWithData:addressData encoding:NSUTF8StringEncoding];
//    NSString *price = [_payButton.titleLabel.text stringByReplacingOccurrencesOfString:@"¥" withString:@""];
//    //    NSLog(@"%@",price);
    
    [model pay:_workName price:totalPriceStr goods:priceJSON body:_workName work_id:_workID address:addressJSON];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
